package top.rushpeak.edu03.websocket.handler;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSONObject;

import top.rushpeak.edu03.api.model.User;
import top.rushpeak.edu03.websocket.result.MsgResult;
import top.rushpeak.edu03.websocket.util.SessionManager;

@Component
public class MyWebSocketHandler implements WebSocketHandler {

	private static final Logger	LOG		= Logger.getLogger(MyWebSocketHandler.class);
	
	private SessionManager sessionManager = SessionManager.instance();
	
	private static final ArrayList<WebSocketSession> users = new ArrayList<WebSocketSession>();
	
	//建立连接时处理
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		LOG.info("建立连接");
		sessionManager.put(session);
//		users.add(session);	
		
		//测试传对象
		MsgResult<User> res = new MsgResult<>();
		res.setCode("0");
		res.setMsgType("test1");
		res.setMessage("testStart");
		User user = new User();
		user.setId(2);
		user.setUsername("test1");
		user.setPassword("123");
		res.setData(user);
		session.sendMessage(new TextMessage(JSONObject.toJSONString(res)));
	
	}

	//接收客户端信息时处理
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		System.out.println("接收到信息："+message.toString());
		LOG.info("接收到信息："+message.toString());
		
		//测试传对象
		MsgResult<User> res = new MsgResult<>();
		res.setCode("0");
		res.setMsgType("test2");
		res.setMessage("testmsg");
		User user = new User();
		user.setId(2);
		user.setUsername("test2");
		user.setPassword("123");
		res.setData(user);
		session.sendMessage(new TextMessage(JSONObject.toJSONString(res)));
		
	}

	//握手出错处理
	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        if(session.isOpen()){  
            session.close();  
        }  
        sessionManager.remove(session);
        
//        users.remove(session);  
          
        LOG.error("握手出错处理" + exception.getMessage()); 
		
	}

	//断开连接处理
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {

        users.remove(session);  
        LOG.debug("断开连接" + closeStatus.getReason());  		
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}
	
    /** 
     * 给所有在线用户发送消息 
     * @param message 
     */  
    public void sendMessageToUsers(TextMessage message) {  
        for (WebSocketSession user : users) {  
            try {  
                if (user.isOpen()) {  
                    user.sendMessage(message);  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    } 	

}
